/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.sixplusone.redblue.web;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.sixplusone.redblue.Generator;
import org.sixplusone.redblue.PreferedNumberGenerator;
import org.sixplusone.redblue.RandomFactory;
import org.sixplusone.redblue.SimpleRandomGenerator;


public class RedblueServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		String seedstr = req.getParameter("seed");
		ArrayList<String> nums = new ArrayList<String>();
		nums.add(req.getParameter("number1"));
		nums.add(req.getParameter("number2"));
		nums.add(req.getParameter("number3"));
		nums.add(req.getParameter("number4"));
		String rate = req.getParameter("rate");
		Generator base;// = new SimpleRandomGeneraor();
		long seed = 0;
		try {
			seed = Long.parseLong(seedstr);
		} catch (NumberFormatException nfe) {
			seed = System.currentTimeMillis() + seedstr.hashCode()*13 ;
		}
		base = new SimpleRandomGenerator();
		ArrayList<Integer> numbers = new ArrayList<Integer>();
		for (String string : nums) {
			int i = Integer.parseInt(string);
			if (i != 0 && !numbers.contains(i)) {
				numbers.add(i);
			}
		}
		if(!numbers.isEmpty()){
			try {
				int[] prefs = new int[numbers.size()];
				for (int i = 0; i < prefs.length; i++) {
					prefs[i]=numbers.get(i);
				}
				
				int rateValue = Integer.parseInt(rate);
				base = new PreferedNumberGenerator(base,prefs,rateValue);
			} catch (NumberFormatException nfe) {
				resp.getWriter().println(rate + " is not valid value for rate");
			}
			
		}
		resp.getWriter().println(base.generate(RandomFactory.getRandom(seed)));
	}

}
